// #include "MrpcLog.h"
#include "MrpcLog.h"
#include <cstdio>
#include <google/protobuf/stubs/mutex.h>
#include <string>
#include "LockQueue.h"
#include <thread>
MrpcLog::MrpcLog(){
    std::thread write_log_thread(
        [&](){
            for(;;){
                time_t now = time(nullptr);
                tm* local_time = localtime(&now);
                char file_name[128];
                sprintf(file_name, "%d-%d-%d-log.txt", local_time->tm_year + 1900, local_time->tm_mon + 1, local_time->tm_mday);
                FILE *fp = fopen(file_name, "a");
                if(fp == nullptr){
                    fprintf(stderr, "log::log() - fopen() failed!\n");
                    return ;
                }

                std::string log_data = this->_log_queue.pop();
                char buf[1024] = {0};
                sprintf(buf,"[%s]%d:%d:%d: ",(_log_level == INFO ? "INFO":"ERROR"), \
                    local_time->tm_hour+1, local_time->tm_min+1, local_time->tm_sec);
                log_data.insert(0,buf);
                log_data.append("\n");
                fputs(log_data.c_str(), fp);//系统调用？
                fclose(fp);    
            }            
        }
    );
    write_log_thread.detach();
    return;
}

MrpcLog& MrpcLog::getInstance(){
    static MrpcLog instance;
    return instance;
}
void MrpcLog::log(std::string data){//
    _log_queue.push(data);
}

void MrpcLog::SetLogLevel(LogLevel level){
    _log_level = level;
}
